package com.yunyouyi.intelligent_vehicle.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyouyi.intelligent_vehicle.common.Result;
import com.yunyouyi.intelligent_vehicle.dto.LoginDTO;
import com.yunyouyi.intelligent_vehicle.entity.User;
import com.yunyouyi.intelligent_vehicle.service.UserService;
import com.yunyouyi.intelligent_vehicle.util.HttpStatus;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Tag(name = "用户管理", description = "用户相关的API接口")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Result<?> login(@Valid @RequestBody LoginDTO loginDTO) {
        User user = userService.login(loginDTO);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error(HttpStatus.UNAUTHORIZED, "用户名或密码错误");
        }
    }    // 查询所有用户
    @Operation(summary = "获取所有用户", description = "返回所有用户的列表")
    @GetMapping("/list")
    public Result<?> list() {
        return Result.success(userService.list());
    }

    // 分页查询用户
    @Operation(summary = "分页查询用户", description = "分页查询用户")
    @GetMapping("/page")
    public Result<IPage<User>> page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        return Result.success(userService.page(page));
    }

    // 根据条件查询用户
    @GetMapping("/query")
    public Result<List<User>> query(@RequestParam("name") String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("name", name);
        return Result.success(userService.list(wrapper));
    }

    // 添加用户
    @Operation(summary = "创建新用户", description = "创建一个新的用户")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "201", description = "用户创建成功",
                    content = @Content(schema = @Schema(implementation = User.class))),
            @ApiResponse(responseCode = "400", description = "无效的用户数据")
    })
    @PostMapping("/add")
    public Result<?> add(@RequestBody User user) {
        //检查用户账号和邮箱是否已存在
        Result<?> check = checkCount(user);
        if (check != null) {
            return check;
        }
        boolean isValid = userService.save(user);
        if (isValid){
            return Result.success("用户创建成功");
        }else{
            return Result.error("无效的用户数据");
        }
    }


    // 更新用户
    @PutMapping("/update")
    public Result<?> update(@RequestBody User user) {
        return Result.success(userService.updateById(user));
    }

    // 删除用户
    @DeleteMapping("/delete/{id}")
    public Result<?> delete(@PathVariable("id") Long id) {
        return Result.success(userService.removeById(id));
    }
    /**
     * 检查用户账号和邮箱是否已存在
     *
     * @param user 用户信息
     * @return 账号已存在返回Result对象，否则返回null
     */
    private Result<Object> checkCount(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", user.getAccount());
        User existUser = userService.getOne(wrapper);
        if (existUser != null) {
            return Result.error("账号已存在");
        }

        QueryWrapper<User> emailWrapper = new QueryWrapper<>();
        emailWrapper.eq("email", user.getEmail());
        User emailExistUser = userService.getOne(emailWrapper);
        if (emailExistUser != null) {
            return Result.error("邮箱已存在");
        }
        return null;
    }
}